<template>
  <a-modal
    :open="props.modelVisible"
    title="创建项目"
    @cancel="handleCancel"
    @ok="handleOk"
    cancel-text="取消"
    ok-text="确定"
    style="width: 40%"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :label-col="{ style: { width: '100px' } }"
      :wrapper-col="{ span: 18 }"
      :rules="rules"
    >
      <a-form-item label="项目名称" name="projectName">
        <a-input v-model:value="formState.projectName" placeholder="请输入项目名称" />
      </a-form-item>
      <a-form-item label="项目描述" name="projectDescription">
        <a-textarea
          v-model:value="formState.projectDescription"
          placeholder="请描述项目(字数:2-200)"
          :autoSize="{ minRows: 4, maxRows: 4 }"
        />
      </a-form-item>
      <a-form-item label="课程项目">
        <a-switch
          v-model:checked="formState.projectType"
          :checkedValue="2"
          :unCheckedValue="1"
          @change="changeType"
        />
      </a-form-item>
      <a-form-item label="负责人">
        <a-select
          v-model:value="formState.leaders"
          mode="multiple"
          placeholder="请选择负责人"
          :showSearch="false"
          :field-names="{ label: 'userName', value: 'userId' }"
          :options="items"
          :listHeight="150"
        >
          <template #dropdownRender="{ menuNode: menu }">
            <a-space style="display: flex; justify-content: center">
              <a-input v-model:value="selectInput" allow-clear @change="findUser"></a-input>
              <a-segmented v-model:value="value" :options="data" />
            </a-space>
            <a-divider style="margin: 4px 0" />
            <v-nodes :vnodes="menu" />
          </template>
        </a-select>
      </a-form-item>
      <a-form-item label="开始时间" name="startTime">
        <a-date-picker v-model:value="formState.startTime" style="width: 100%" show-time />
      </a-form-item>
      <a-form-item label="项目期限">
        <a-date-picker v-model:value="formState.endTime" style="width: 100%" show-time />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import dayjs from 'dayjs';
import type { Rule } from 'ant-design-vue/es/form';
import type { UnwrapRef } from 'vue';
import ProjectDao from '@/daos/project_dao';
import { message } from 'ant-design-vue';
import UserDao from '@/daos/user_dao';
import { useStore } from 'vuex';
import { onMounted, watch } from 'vue';
const store = useStore();
const projectDao = new ProjectDao();
const userDao = new UserDao();
const formRef = ref();
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  }
});
const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes;
  }
});
const emit = defineEmits(['update:modelVisible', 'confirm']);

interface FormState {
  projectName: string;
  projectDescription: string;
  projectType: number;
  creatorId: number;
  leaders: number[];
  startTime: dayjs.Dayjs;
  endTime: dayjs.Dayjs;
}

const formState: UnwrapRef<FormState> = reactive({
  projectName: '',
  projectDescription: '',
  projectType: 1,
  creatorId: store.getters.userId,
  leaders: [store.getters.userId],
  startTime: undefined,
  endTime: undefined
});

const selectInput = ref();
const items = ref([
  { userName: store.getters.userName, userId: store.getters.userId, disabled: true }
]);

const changeType = () => {
  formState.leaders = [store.getters.userId];
  items.value = [
    { userName: store.getters.userName, userId: store.getters.userId, disabled: true }
  ];
  // 根据项目类型加载不同角色的成员
  findUser();
};

//查询用户
const data = reactive(['用户编号', '名称', '手机号']);
const value = ref(data[0]);
const findUser = async () => {
  const queryParams = {
    用户编号: { userId: selectInput.value, name: null, phone: null },
    名称: { userId: null, name: selectInput.value, phone: null },
    手机号: { userId: null, name: null, phone: selectInput.value }
  }[value.value];
  
  try {
    let result;
    // 根据项目类型查询不同类型的用户
    if (formState.projectType == 1) {
      // 普通项目 - 查询所有类型用户
      result = await userDao.findUser(
        queryParams?.userId,
        queryParams?.name,
        queryParams?.phone,
        formState.projectType,
        null
      );
    } else {
      // 课程项目 - 只查询教师类型用户
      result = await userDao.findUser(
        queryParams?.userId,
        queryParams?.name,
        queryParams?.phone,
        formState.projectType,
        1 // 教师类型
      );
    }

    if (result.data.code === 200) {
      items.value = result.data.data || [];
      // 在数据开头插入当前用户信息
      items.value = items.value.filter((item) => item.userId !== store.getters.userId);
      items.value.unshift({
        userName: store.getters.userName,
        userId: store.getters.userId,
        disabled: true
      });
    } else {
      message.error('获取用户列表失败');
    }
  } catch (error) {
    console.error('查询用户失败:', error);
    message.error('查询用户失败');
  }
};

// 在组件挂载时初始化用户列表
onMounted(() => {
  // 初始加载用户列表
  if (props.modelVisible) {
    findUser();
  }
});

// 监听模态框显示状态，当打开时重新加载用户列表
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue) {
      // 重置表单
      formRef.value?.resetFields();
      // 重置用户列表
      formState.projectType = 1;
      formState.leaders = [store.getters.userId];
      formState.startTime = undefined;
      formState.endTime = undefined;
      // 加载用户列表
      findUser();
    }
  }
);

const handleOk = () => {
  formRef.value
    .validate()
    .then(async () => {
      const result = await projectDao.createProject(toRaw(formState));
      console.log(result.data.data);
      if (result.data.code === 200) {
        message.success(result.data.data);
        //更新窗口状态，false为关闭
        emit('update:modelVisible', false);
        //更新任务页面内容
        emit('confirm');
        formRef.value.resetFields();
      } else {
        message.error(result.data.data);
      }
    })
    .catch((error) => {
      console.log('error', error);
    });
};
const handleCancel = () => {
  emit('update:modelVisible', false);
  formRef.value.resetFields();
};
const rules: Record<string, Rule[]> = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectDescription: [
    { required: true, message: '请描述项目', trigger: 'blur' },
    { min: 2, max: 200, message: '字数:2-200', trigger: 'blur' }
  ]
};
</script>
